import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Upload, Row, Col, Card, Form, Input, Select, Icon, Button, Dropdown, Menu, InputNumber, DatePicker, Modal, message } from 'antd';
import StandardTable from './StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './StudentList.less';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

@connect(state => ({
  exam: state.exam,
  student: state.student,
}))
@Form.create()
export default class StudentList extends PureComponent {
  state = {
    filePath: '',
    modalVisible: false,
    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'student/fetch',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'student/fetch',
      payload: params,
    });
  }

  handleDelMenuClick = (e) => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    if (!selectedRows) return;

    dispatch({
      type: 'student/remove',
      payload: {
        id: selectedRows.map(row => row.id).join(','),
      },
      callback: () => {
        this.setState({
          selectedRows: [],
        });
      },
    });
  }

  handleSelectRows = (rows) => {
    this.setState({
      selectedRows: rows,
    });
  }

  handleModalVisible = (flag) => {
    this.setState({
      modalVisible: !!flag,
    });
  }


  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      console.log(values);
      if (!err) {
        const params = values;
        params.file_path = this.state.filePath;
        this.props.dispatch({
          type: 'student/add',
          payload: params,
          callback: () => {
            message.success('添加成功');
            // window.location.reload();
            this.setState({
              modalVisible: false,
            });
          },
        });
      }
    });
  }

  render() {
    const { student: { loading: studentLoading, data }, exam: {list} } = this.props;
    const { selectedRows, modalVisible } = this.state;
    const { getFieldDecorator } = this.props.form;
    const props = {
      name: 'file_name',
      action: '/upload',
      onChange: (info) => {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          message.success(`${info.file.name} file uploaded successfully`);
          this.setState({
            filePath: info.file.response.data
          })
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} file upload failed.`);
        }
      },
    };

    const formItemLayout = {
      labelCol: {
        span: 5,
      },
      wrapperCol: {
        span: 15,
      },
    };

    return (
      <PageHeaderLayout title="学员列表">
        <Card bordered={false}>
          <div className={styles.StudentList}>
            <div className={styles.StudentListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新增学员
              </Button>
              {
                selectedRows.length > 0 && (
                  <span>
                    <Button key="remove" onClick={this.handleDelMenuClick}>删除</Button>
                  </span>
                )
              }
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={studentLoading}
              data={data}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <Modal
          title="新增学员"
          visible={modalVisible}
          onOk={this.handleSubmit}
          onCancel={() => this.handleModalVisible()}
        >
          <Form
            hideRequiredMark
            style={{ marginTop: 8 }}
          >

            <FormItem
              {...formItemLayout}
              label="考试ID"
            >
              {getFieldDecorator('exam_id', {
                rules: [{
                  required: true, message: '请选择考试',
                }],
              })(
                <Select>
                  {
                    list && list.map((item) => {
                      return <Option value={item.id}>{item.name}</Option>
                    })
                  }
                </Select>
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="考场名称"
            >
              {getFieldDecorator('room_name', {
                rules: [{
                  required: true, message: '请输入考场名称',
                }],
              })(
                <Input placeholder="请输入考场名称" />
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="学员文件"
            >
              {getFieldDecorator('file_path', {
                rules: [{
                  required: true, message: '请选择文件',
                }],
              })(
                <Upload {...props}>
                  <Button>
                    <Icon type="upload" /> Click to Upload
                  </Button>
                </Upload>
              )}
            </FormItem>
          </Form>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
